<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>机构信息管理</span>
        <div class="extra">
          <el-button type="primary" @click="add">新增机构</el-button>
        </div>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="机构名称:">
        <el-input v-model="agency.name" placeholder="请输入机构名" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="机构编号:">
        <el-input v-model="agency.id" placeholder="请输入机构编号" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="机构类型">
        <el-select v-model="agency.type" placeholder="请选择类型" style="width: 200px">
          <el-option v-for="item in agencyTypeList" :key="item.id" :label="item.name" :value="item.name" />
        </el-select>
        <el-button type="primary" @click="show" style="margin-left: 15px;">搜索</el-button>
        <el-button @click="clear">重置</el-button>
        <el-button type="danger" @click="deleteByIds">批量删除</el-button>
      </el-form-item>

    </el-form>

    <el-table ref="multipleTable" @selection-change="handleSelectionChange" :data="tableData" style=" width: 100%;">
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="id" label="编号" width="80px"></el-table-column>
      <el-table-column prop="name" label="机构名"></el-table-column>
      <el-table-column prop="type" label="类型"></el-table-column>
      <el-table-column label="操作" header-align="center" align="center" width="250">
        <template slot-scope="scope">
          <el-button class="el-icon-edit" type="primary" circle plain @click="updateInfo(scope.row.id)">
          </el-button>
          <el-button class="el-icon-delete" type="danger" circle plain @click="deleteById(scope.row.id)">
          </el-button>
          <el-button class="el-icon-user" type="primary" circle plain @click="addForAgency(scope.row.id)">
          </el-button>
          <el-button class="el-icon-document" type="primary" circle plain @click="addList(scope.row.id)">
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
                <el-empty description="没有数据" />
            </template>
    </el-table>


    <el-pagination style="margin-top: 20px;text-align: right;" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" :background="background" :current-page="currentPage" :page-sizes="[5, 10]"
      :page-size="5" layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
    </el-pagination>




    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="close" width="30%">
      <el-form :model="agency">
        <el-form-item label="机构名称" :label-width="formLabelWidth" :rules="[{ required: true }]">
          <el-input v-model="agency.name" placeholder="请输入机构名..." autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="机构类型" :label-width="formLabelWidth" :rules="[{ required: true }]">
          <el-select v-model="agency.type" placeholder="请选择..." style="width:100%">
            <el-option v-for="item in agencyTypeList" :key="item.value" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addForm"> 确认 </el-button>
        </span>
      </template>

    </el-dialog>

    <!-- 分配账户     -->
    <el-dialog title="账户分配" :visible.sync="addForAgencyVisible" :before-close="closeAddForAgencyVisible" width="21%">
      <el-form :model="addCount" :label-width="'170px'">
        <el-form-item label="机构管理员账户数量：" :rules="[{ required: true }]">
          <el-input-number size="medium" style="width: 100%" v-model="addCount.firstNum" :min="0" :max="10"
            label="请输入机构管理员账户数量"></el-input-number>
        </el-form-item>
        <el-form-item label="机构发布员账户数量：" :rules="[{ required: true }]">
          <el-input-number size="medium" style="width: 100%" v-model="addCount.secondNum" :min="0" :max="10"
            label="请输入机构发布员账户数量"></el-input-number>
        </el-form-item>
        <el-form-item label="机构审核员账户数量：" :rules="[{ required: true }]">
          <el-input-number size="medium" style="width: 100%" v-model="addCount.thirdNum" :min="0" :max="10"
            label="请输入机构审核员账户数量"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAddForAgencyVisible()">取消</el-button>
        <el-button type="primary" @click="addForAgencys()">确定</el-button>
      </div>
    </el-dialog>
    <!-- 配置咨询列表     -->
    <el-dialog title="配置咨询列表配置" :visible.sync="addListVisible" :before-close="closeAddListVisible">

      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="未配置列表" name="first">
          <el-form>
            <el-button style="float: left" type="primary" @click="chooseConsultByIds"
              v-show="searchChoose">批量配置</el-button>
          </el-form>
          <el-table highlight-current-row ref="consultTable" @selection-change="consultSelectionChange"
            :data="consultData" style="margin: 0 auto; width: 100%;">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="编号" header-align="center" align="center" width="80"></el-table-column>
            <el-table-column prop="question" label="问题" header-align="center" align="center"></el-table-column>
            <el-table-column prop="answer" label="回答" header-align="center" align="center"></el-table-column>
            <el-table-column label="操作" width="100" header-align="center" align="center">
              <template slot-scope="scope">
                <el-button class="el-icon-check" type="primary" circle plain @click="chooseConsults(scope.row.id)"
                  v-show="searchChoose">
                </el-button>

                <el-button class="el-icon-delete" type="danger" circle plain @click="unchooseConsults(scope.row.id)"
                  v-show="!searchChoose">
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 周报表单 -->
        <el-tab-pane label="已配置列表" name="second">
          <el-button style="float: left" type="danger" @click="unchooseConsultByIds">批量删除</el-button>
          <el-table highlight-current-row ref="consultTable" @selection-change="consultSelectionChange"
            :data="consultData" style="margin: 0 auto; width: 100%;">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="编号" header-align="center" align="center" width="80"></el-table-column>
            <el-table-column prop="question" label="问题" header-align="center" align="center"></el-table-column>
            <el-table-column prop="answer" label="回答" header-align="center" align="center"></el-table-column>
            <el-table-column label="操作" width="100" header-align="center" align="center">
              <template slot-scope="scope">
                <el-button class="el-icon-check" type="primary" circle plain @click="chooseConsults(scope.row.id)"
                  v-show="searchChoose">
                </el-button>

                <el-button class="el-icon-delete" type="danger" circle plain @click="unchooseConsults(scope.row.id)"
                  v-show="!searchChoose">
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>



      </el-tabs>
    </el-dialog>


  </el-card>




  <!--分页工具条-->




</template>
<script>


import { addAgency, changeAgency, deleteAgency, getAllAgency } from "@/api/agency";
import { addUserForAgency } from "@/api/user";
import { getAgencyTypeList } from "@/api/agencyType";
import { chooseConsult, getConsultList, getConsultListForAgency, unchooseConsult } from "@/api/consult";

export default {
  data() {
    return {
      activeTab: 'first',
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      // 表格数据
      tableData: [],
      addOrUpdate: true,//true为add
      agency: {},
      form: {},
      posts: [],
      multipleSelection: [],
      consultSelection: [],
      selectedIds: [],
      agencyList: [],
      agencyTypeList: [],
      formLabelWidth: "80px",
      addForAgencyVisible: false,
      addCount: { "firstNum": 0, "secondNum": 0, "thirdNum": 0 },
      addCountId: 0,
      addListVisible: false,
      consultData: [],
      searchChoose: true,
    }
  },
  watch: {
    searchChoose(newValue, oldValue) {
      this.getConsultData();
    }
  },
  methods: {
    show() {
      getAllAgency(this.agency, this.currentPage, this.pageSize).then((res) => {
        if (res.data.code === 1) {
          this.totalCount = res.data.data.total;
          this.tableData = res.data.data.rows;
          //console.log(this.tableData)
          if (this.tableData.length === 0 && this.currentPage > 1) {
            this.currentPage -= 1;
            this.show();
          }
        }
      }).catch((e) => {
      })
    },
    handleTabClick(tab) {
      // tab 对象包含被点击的标签页的信息
      // tab.name 将是 'first' 或 'second'
      if (tab.name === 'first') {
        // 如果是第一个标签页，执行 chooseConsultByIds 函数
        this.searchChoose = true;
        getConsultListForAgency(this.addCountId, this.searchChoose).then((res) => {
          if (res.data.code === 1) {
            this.consultData = res.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch((e) => {
        })
      } else if (tab.name === 'second') {
        // 如果是第二个标签页，执行 unchooseConsultByIds 函数
        this.searchChoose = false;
        getConsultListForAgency(this.addCountId, this.searchChoose).then((res) => {
          if (res.data.code === 1) {
            this.consultData = res.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch((e) => {
        })
      }
    },

    clear() {
      this.agency = {};
      this.show();
    },
    add() {
      this.agency = {};
      this.addOrUpdate = true;
      this.dialogVisible = true;
      this.title = '新增机构';
    },
    addForm() {
      if (this.addOrUpdate) {
        addAgency(this.agency).then(res => {
          if (res.data.code === 1) {
            this.$message.success("保存成功")
            this.dialogVisible = false;
            this.show();
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(e => {
        });
      } else {
        //更新
        changeAgency(this.agency).then(res => {
          console.log(res)
          if (res.data.code === 1) {
            this.$message.success("更新成功")
            this.dialogVisible = false;
            this.show()
          }
        }).catch(e => {
        });
      }

    },
    close() {
      this.dialogVisible = false;
      this.agency = {}
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    updateInfo(id) {
      this.addOrUpdate = false;
      this.agency = this.tableData.filter(data => data.id == id)[0];
      this.dialogVisible = true;
      this.title = '编辑机构';
    },
    deleteById(id) {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(this.tableData.filter(data => data.id === id)[0]);
      this.deleteByIds()
    },
    deleteByIds() {
      // 弹出确认提示框
      this.$confirm("你确认删除该条信息吗？", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //用户点击确认按钮
        //1. 创建id数组, 从 this.multipleSelection 获取即可
        for (let i = 0; i < this.multipleSelection.length; i++) {
          this.selectedIds[i] = this.multipleSelection[i].id;
        }
        //console.log(this.selectedIds);
        deleteAgency(this.selectedIds).then((resp) => {
          if (resp.data.code == "1") {
            //删除成功
            this.$message.success("删除成功");
            this.clear();
          } else {
            this.$message.error(resp.data.msg);
          }
        }).catch(() => {
        });

      }).catch(() => {
        //用户点击取消按钮
        this.$message.info("取消删除");
      });

    },
    //分配账户
    addForAgency(id) {
      this.addCountId = id;
      this.addForAgencyVisible = true;
    },
    closeAddForAgencyVisible() {
      this.addForAgencyVisible = false;
      // this.addCount = -1
    },
    addForAgencys() {
      addUserForAgency(this.addCount.firstNum, this.addCount.secondNum, this.addCount.thirdNum, this.addCountId).then((res) => {
        if (res.data.code === 1) {
          this.$message.success("分配成功");
          this.addForAgencyVisible = false;
        }
      }).catch((e) => {
      })
    },
    //配置咨询列表
    addList(id) {
      this.addCountId = id;
      this.addListVisible = true;
      this.getConsultData();
    },
    closeAddListVisible() {
      this.addListVisible = false;
      this.addCount = -1
      this.consultData = [];
    },
    getConsultData() {
      getConsultListForAgency(this.addCountId, this.searchChoose).then((res) => {
        if (res.data.code === 1) {
          this.consultData = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch((e) => {
      })
    },
    consultSelectionChange(val) {
      this.consultSelection = val;
    },
    chooseConsults(id) {
      this.$refs.consultTable.clearSelection();
      this.$refs.consultTable.toggleRowSelection(this.consultData.filter(data => data.id === id)[0]);
      this.chooseConsultByIds()
    },
    chooseConsultByIds() {
      let selectedIds = [];
      //1. 创建id数组, 从 this.consultSelection 获取即可
      for (let i = 0; i < this.consultSelection.length; i++) {
        selectedIds[i] = this.consultSelection[i].id;
      }
      //console.log(selectedIds)
      chooseConsult(selectedIds, this.addCountId).then((resp) => {
        if (resp.data.code === 1) {
          //配置成功
          this.$message.success("配置成功");
          this.getConsultData();
        } else {
          this.$message.error(resp.data.msg);
        }
      }).catch(() => {
      });
    },
    unchooseConsults(id) {
      this.$refs.consultTable.clearSelection();
      this.$refs.consultTable.toggleRowSelection(this.consultData.filter(data => data.id === id)[0]);
      this.unchooseConsultByIds()
    },
    unchooseConsultByIds() {
      // 弹出确认提示框
      this.$confirm("你确认删除该条信息吗？", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let selectedIds = [];
        //1. 创建id数组, 从 this.consultSelection 获取即可
        for (let i = 0; i < this.consultSelection.length; i++) {
          selectedIds[i] = this.consultSelection[i].id;
        }
        unchooseConsult(selectedIds).then((resp) => {
          if (resp.data.code === 1) {
            //配置成功
            this.$message.success("删除成功");
            this.getConsultData();
          } else {
            this.$message.error(resp.data.msg);
          }
        }).catch(() => {
        });

      }).catch(() => {
        //用户点击取消按钮
        this.$message.info("取消删除");
      });
    },
    //获取机构类型
    getAllAgencyType() {
      getAgencyTypeList().then((res) => {
        if (res.data.code === 1) {
          this.agencyTypeList = res.data.data;
          //console.log(this.agencyTypeList)
        }
      }).catch((e) => {
      })
    },
    //分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val;
      this.show();
    },
    handleCurrentChange(val) {
      // 重新设置当前页码
      this.currentPage = val;
      this.show();
    },


  },
  mounted() {
    this.getAllAgencyType();
    this.show();
    this.getAllAgencyType();
  },
};
</script>


<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}


.basic-info-container {
  display: flex; // 使用flex布局
  flex-wrap: wrap; // 允许元素换行
  margin-right: -10px; // 调整外边距以对齐
}

.basic-info-border,
.basic-info-border2 {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  position: relative;
  padding-top: 30px;
  margin-bottom: 20px; // 添加底部外边距
  width: 100%; // 设置宽度为100%，或者您可以设置一个固定的宽度
  box-sizing: border-box; // 确保padding和border包含在宽度内
}

.basic-info-border::before,
.basic-info-border2::before {
  content: "";
  position: absolute;
  top: -15px;
  left: 10px;
  background-color: #409EFF;
  color: white;
  padding: 5px;
  border-radius: 3px;
  font-weight: bold;
}

.basic-info-border::before {
  content: "基本信息";
}

.basic-info-border2::before {
  content: "客户关键人物信息";
}

// 如果需要，可以为两个框设置最大宽度
.max-width-box {
  max-width: 900px; // 或者您希望的任何宽度
}
</style>
<script setup>
</script>
